//
//  NodataView.swift
//  Wanke
//
//  Created by BO ZHOU on 2020/11/2.
//

import UIKit


open class NodataView: UIView {
    
    
    /** 无数据图片y轴方向上偏移值, 负数表示向上, 正数表示向下 */
    var y_offset_value: CGFloat = 0 {
        didSet {
            self.setNeedsLayout()
        }
    }
    
    /** 记录索引值, 每显示一次 +1, 每hide一次 -1, 如果为0则隐藏 */
    var indexTag: Int = 0

    lazy var scrollview: UIScrollView = {
       
        let scrollview = UIScrollView()
        return scrollview
    }()
    
    lazy var nodataImageView: UIImageView = {
       
        let imageview = UIImageView()
        
        imageview.imageName = "插画_无数据"
        return imageview
    }()
    
    
    lazy var nodataLabel: UILabel = {
        let label = UILabel()
        
        let string = "暂无数据"

        
        let att = NSMutableAttributedString.init(string: string)
        // 设置字体大小
        att.mc_addFont(UIFont.mediumFont(size: 15), on: NSRange.init(location: 0, length: string.count))
        // 设置字体颜色
        att.mc_addForegroundColor(UIColor.white.withAlphaComponent(0.45), range: NSRange.init(location: 0, length: string.count))

        label.attributedText = att
        label.sizeToFit()
        label.textAlignment = .center
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(scrollview)
        scrollview.addSubview(nodataImageView)
        scrollview.addSubview(nodataLabel)
    }
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        scrollview.frame = self.bounds
        let width = 180 * self.width/SCREEN_WIDTH
        nodataImageView.size = CGSize(width: width, height: width / 180 * 140)
        nodataImageView.center = CGPoint(x: self.width/2, y: self.height/2 - 30 + y_offset_value)
        
        nodataLabel.frame = CGRect(x: 0, y: nodataImageView.frame.maxY + 20, width: self.width, height: nodataLabel.height)
    }
    
    
    
    func showSelf() {
        
        indexTag += 1
        
        self.frame = self.superview?.bounds ?? KEY_WINDOW!.bounds
        
        self.superview?.bringSubviewToFront(self)
        
        if self.alpha == 0 {
            animation {
                self.alpha = 1
            }
        }
    }
    
    func hideSelf() {
        
        indexTag -= 1
        
        if indexTag == 0 {
            
            if self.alpha == 1 {
                animation {
                    self.alpha = 0
                }
            }
        }
    }
}
